﻿using System.ComponentModel;
using System.Dynamic;

namespace EasyXaf.DynamicForm.Blazor;

public static class ExpandoObjectExtensions
{
    public static PropertyDescriptorCollection ToPropertyDescriptorCollection(this ExpandoObject expando)
    {
        var propertyDescriptors = new List<PropertyDescriptor>();
        var dictionary = (IDictionary<string, object>)expando;
        foreach (var kvp in dictionary)
        {
            propertyDescriptors.Add(new ExpandoObjectPropertyDescriptor(kvp.Key, dictionary));
        }
        return new PropertyDescriptorCollection([.. propertyDescriptors]);
    }

    private class ExpandoObjectPropertyDescriptor : PropertyDescriptor
    {
        private readonly IDictionary<string, object> _obj;

        public ExpandoObjectPropertyDescriptor(string name, IDictionary<string, object> obj)
            : base(name, null)
        {
            _obj = obj;
        }

        public override Type PropertyType => _obj[Name]?.GetType();

        public override object GetValue(object component) => _obj[Name];

        public override void SetValue(object component, object value) => _obj[Name] = value;

        public override void ResetValue(object component) => throw new NotImplementedException();

        public override bool ShouldSerializeValue(object component) => true;

        public override bool CanResetValue(object component) => false;

        public override Type ComponentType => typeof(ExpandoObject);

        public override bool IsReadOnly => false;
    }
}
